/**
 * Created by Alice on 2016/9/13 0013
 */
;-function (window) {
    "use strict";
    //TODO 预设变量写这里，全局变量写在base.js 里面 使用 r. 调用
    var ready = {
        layer: null,
        judge: [],
        judge_name: [],
        courtrooms: [],
        courtrooms_name: [],
        page_size: 12,
        init_date: null,
        dept: [],
        dept_name: [],
        secretary: [],
        secretary_name: [],
        now_judge: [],
        now_judge_name: []
    };
    //TODO 初始化的方法写这里面
    var init = function () {
        init_ready();//加载预设变量

        var currentDay = utils.get_date(0);
        //查询的开始时间默认给今天
        $('#startTime').datetimepicker({
            bootcssVer: 3,
            minView: "month", //选择日期后，不会再跳转去选择时分秒
            weekStart: "1",
            format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
            language: 'zh-CN', //汉化
            autoclose: true //选择日期后自动关闭
        }).on('changeDate', function (ev) {
            console.log(ev.date.valueOf());
        });
        $('#endTime').datetimepicker({
            bootcssVer: 3,
            minView: "month", //选择日期后，不会再跳转去选择时分秒
            weekStart: "1",
            format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
            language: 'zh-CN', //汉化
            autoclose: true //选择日期后自动关闭
        }).on('changeDate', function (ev) {
            console.log(ev.date.valueOf());
        });
        init_event();
        function init_event() {//TODO 初始化页面事件
            $("#startTime").find("input").val(currentDay);
            $("#endTime").find("input").val(currentDay);
            Class.select_all_group();
            Class.select_all_judges();
            // Class.init_push();
            $("#conditionBtn").click(function () {
                $("#loading").show();
                Class.count_case();
            });
        }

        function init_ready() {//TODO 初始化预设值
            layui.use('layer', function () {
                ready.layer = layui.layer;
            });
            var judge_id = utils.get_url_param("judge");
            judge_id ? ready.judge.push(judge_id) : '';
            var courtroom_id = utils.get_url_param("courtroom_id");
            courtroom_id ? ready.courtrooms.push(courtroom_id) : '';
            if (deptAndPost) {
                $.each(deptAndPost, function (n, dept) {
                    if (dept.deptId && ready.dept.indexOf(dept.deptId) < 0) {
                        ready.dept.push(dept.deptId);
                        ready.dept_name.push(dept.deptName);
                    }
                    if (ready.judge.indexOf(dept.userUid) < 0 && "法官" == dept.postName) {
                        ready.judge.push(dept.userUid);
                        ready.judge_name.push(dept.userName);
                    }
                    if (ready.secretary.indexOf(dept.userUid) < 0 && "书记员" == dept.postName) {
                        ready.secretary.push(dept.userUid);
                        ready.secretary_name.push(dept.userName);
                    }
                });
            }
        }
    };
    //TODO 内部调用的方法写这里
    var Class = {
        select_all_group: function () {
            $('#loading').hide();
            var dropmenu_dept = $('#dropmenu_dept').empty();
            dropmenu_dept.append('<option value="" selected>所有部门</option>');
            if (deptAndPost) {
                $.each(ready.dept, function (index, dept) {
                    dropmenu_dept.append('<option value="' + dept + '" >' + ready.dept_name[index] + '</option>');
                    // dropmenu_dept.append('<li><a href="javascript:;" onclick="p.dept_change(\'' + dept.uid + '\')">' + dept.deptname + '</a></li>');
                })
            }
        },
        select_all_judges: function () {
            if (deptAndPost) {
                ready.init_data = deptAndPost;
                var dropmenu_judge = $('#allJudges').empty();
                dropmenu_judge.append('<option value="" selected>所有法官</option>');
                var dropmenu_courtroom = $('#allCourtRooms').empty();
                dropmenu_courtroom.append('<option value="" selected>所有法庭</option>');
                var dropmenu_secretary = $("#allSecretary").empty();
                dropmenu_secretary.append('<option value="" selected>所有书记员</option>');
                $.each(deptAndPost, function (index, dept) {
                    if (dept.userUid && dept.postName == "法官") {
                        if (ready.now_judge.indexOf(dept.userUid) < 0) {
                            ready.now_judge.push(dept.userUid);
                            ready.now_judge_name.push(dept.userName);
                            dropmenu_judge.append('<option value="' + dept.userUid + '" >' + dept.userName + '</option>');
                        }
                    }
                });
                $.each(ready.secretary, function (no, secretary) {
                    dropmenu_secretary.append("<option value='" + secretary + "'>" + ready.secretary_name[no] + "</option>");
                });
                if (courtroomList) {
                    $.each(courtroomList, function (index, courtroom) {
                        dropmenu_courtroom.append('<option value="' + courtroom.uid + '" >' + courtroom.name + '</option>');
                        ready.courtrooms.push(courtroom.uid);
                        ready.courtrooms_name.push(courtroom.name);
                    })
                } else {
                    $('#allCourtRooms').html('无法庭');
                }
                Class.select_case_type();
                //加载数据
                Class.count_case();

                // Class.select_secretary();
            }
        },
        dept_change: function (dept_uid) {
            // console.info(ready.init_data.dept);
            // console.info(dept_uid);
            ready.now_judge = [];
            ready.now_judge_name = [];
            var dropmenu_judge = $('#allJudges').empty();
            dropmenu_judge.append('<option value="" selected>所有法官</option>');
            var dropmenu_secretary = $("#allSecretary").empty();
            dropmenu_secretary.append('<option value="" selected>所有书记员</option>');
            // dropmenu_judge.append('<li><a href="javascript:;" onclick="p.judge_change(\'sometimes_everything_is_ok\')">所有法官</a></li>');
            // $('#dropmenu_judge').find('a').eq(0).html('所有法官 <span class="caret"></span>');
            if (dept_uid == '') {
                //法官的下拉框
                $.each(ready.dept, function (index, dept) {
                    dropmenu_dept.append('<option value="' + dept + '" >' + ready.dept_name[index] + '</option>');
                    // dropmenu_judge.append('<li><a href="javascript:;" onclick="p.judge_change(\'' + dept.userId + '\')">' + dept.username + '</a></li>');
                    ready.now_judge.push(dept.judge);
                    ready.now_judge_name.push(dept.judge_name);
                });
                //书记员下拉框
                $.each(ready.secretary, function (index, secretary) {
                    dropmenu_secretary.append('<option value="' + secretary + '" >' + ready.secretary_name[index] + '</option>');
                })

            } else {
                // var dept_no = ready.dept.indexOf(dept_uid);
                // $('#dropmenu_dept').find('a').eq(0).html(ready.dept_name[dept_no] + ' <span class="caret"></span>');
                //法官的下拉框
                $.each(deptAndPost, function (index, dept) {
                    if (dept.deptId == dept_uid && dept.postName == "法官") {
                        dropmenu_judge.append('<option value="' + dept.userUid + '" >' + dept.userName + '</option>');
                    }

                });
                //书记员下拉框
                $.each(deptAndPost, function (index, dept) {
                    if (dept.deptId == dept_uid && dept.postName == "书记员") {
                        dropmenu_secretary.append('<option value="' + dept.userUid + '" >' + dept.userName + '</option>');
                    }
                });
            }
        },
        select_case_type: function () {
            if (caseTypeList) {
                var case_type = $("#caseTypeName").empty();
                case_type.append("<option value=''>" + "所有类型" + "</option>");
                $.each(caseTypeList, function (i, valueOfElement) {
                    case_type.append("<option value='" + valueOfElement.uid + "'>" + valueOfElement.name + "</option>");
                });
            }
        },
        select_secretary: function () {
            var select_secretary = $("#allSecretary").empty();
            $.get(r.base_path + "trial/selectAllSecretaries", {
                courtId: r.court_id
            }, function (result) {
                if (result.data) {
                    select_secretary.append("<option value=''>" + "所有书记员" + "</option>");
                    $.each(result.data, function (i, valueOfElement) {
                        select_secretary.append("<option value='" + valueOfElement.uid + "'>" + valueOfElement.username + "</option>");
                    });
                }
            }, 'json');
        },

        count_case: function (pageIndex) {
            if (!pageIndex) {
                pageIndex = 1;
            }
            var caseno = $("#caseno").val();
            var caseName = $("#caseName").val();
            var caseTypeName = $("#caseTypeName").val();
            var courtRoom = $("#allCourtRooms").val();
            // var deptId = $("#dropmenu_dept").val();
            var judgeIds = [];
            if ($("#allJudges option:selected").val() == '' && $("#dropmenu_dept option:selected").val() == '') {

            } else if ($("#allJudges option:selected").val() == '') {
                $("#allJudges option").each(function () {  //遍历所有option
                    var judgeId = $(this).val();   //获取option值
                    if (judgeId != '') {
                        judgeIds.push(judgeId);  //添加到数组中
                    }
                });
            } else {
                judgeIds.push($("#allJudges option:selected").val());
            }
            var secretarys = [];
            if ($("#allSecretary option:selected").val() == '' && $("#dropmenu_dept option:selected").val() == '') {

            } else if ($("#allSecretary option:selected").val() == '') {
                // $("#allSecretary option").each(function () {  //遍历所有option
                //     var st = $(this).val();   //获取option值
                //     if (st != '') {
                //         secretarys.push(st);  //添加到数组中
                //     }
                // });
            } else {
                secretarys.push($("#allSecretary option:selected").val());
            }
            // var secretary = ready.secretary||$("#allSecretary").val();
            var startTime = $("#startTime").find("input").val();
            var endTime = $("#endTime").find("input").val();
            // console.log(caseName, caseTypeName, courtRoom, judge, secretary, startTime, endTime);
            var row_no_padding = $(".row-no-padding").empty();
            $.ajax({
                url: r.base_path + "judge/selectMoreCasePlanOrReview",
                type: "get",
                dataType: "json",
                data: {
                    courtUid: r.user_court_uid,
                    archives: caseno,
                    caseName: caseName,
                    type: caseTypeName,
                    courtRoom: courtRoom,
                    judgeList: judgeIds.toString(),
                    // secretaryList: secretarys.toString(),
                    secretaryId: secretarys[0],
                    startDate: startTime,
                    endDate: endTime,
                    status: 0,
                    review: 0,
                    page: pageIndex,
                    pageSize: ready.page_size
                },
                success: function (result) {
                    // console.log(result.data);
                    var s = result.data.count;
                    if (s == 0) {
                        Class.page(1, 1, null);
                    } else {
                        Class.page(pageIndex, Math.ceil(s / 12), Class.count_case);
                    }


                    if (result.code == 0) {
                        if (result.data.count <= 0) {
                            row_no_padding.append('<span>暂无开庭信息</span>');
                        } else {
                            var picNum = 6;
                            $.each(result.data.data, function (i, valueOfElement) {
                                var caseName = valueOfElement.name;
                                var startDate = valueOfElement.startDate;
                                var status = valueOfElement.status;
                                var courtroom_name = valueOfElement.courtroomName;
                                var cid = valueOfElement.courtroomUid;
                                var statusName = "";
                                if (0 == status) {
                                    statusName = "排期";
                                } else if (1 == status || 5 == status) {
                                    statusName = "开庭";
                                } else if (2 == status) {
                                    statusName = "休庭";
                                } else if (3 == status) {
                                    statusName = "闭庭";
                                } else {
                                    statusName = "归档";
                                }
                                var randomNum = parseInt(picNum * Math.random() + 1);//随机出1到picNum的整数
                                var href = r.base_path + "archives/living?planUid=" + valueOfElement.planUid + "&courtroomUid=" + cid;
                                var html = '<div class="col-md-2 col-xs-6">' +
                                    '<div class="more-courting-item">' +
                                    '<a href="' + href + '">' +
                                    '<div class="more-courting-item-img-panel">' +
                                    '<p class="more-courting-item-img-panel-top">' + (courtroom_name ? courtroom_name : '未知') + '</p>' +
                                    '<img src="' + r.base_path + "assets/img/more_court_test" + randomNum + ".jpg" + '" alt="法院">' +
                                    '<p class="more-courting-item-img-panel-bottom" >' + statusName + '</p>' +
                                    '</div>' +
                                    '<p id="startDate">' + startDate + '</p>' +
                                    '<p id="caseNoDis">' + (valueOfElement.archives ? valueOfElement.archives : '未知') + '</p>' +
                                    '<p class="more-courting-item-depiction">' +
                                    // '<i class="fa fa-exchange cursor-hand" title="推送" id="' + valueOfElement.uid + '"></i>' +
                                    '<span>' + (caseName ? caseName : "&nbsp;") + '</span>' +
                                    '</p>' +
                                    '</a>' +
                                    '</div>' +
                                    '</div>';
                                row_no_padding.append(html);
                            });
                            $('.fa-exchange').click(function (e) {
                                e.preventDefault();
                                // console.log();
                                $('#_uid').val(this.id);
                                $("#_detail").modal("show");
                            })
                        }
                        $("#loading").hide();
                        row_no_padding.show();
                    } else {
                        $("#loading").hide();
                        row_no_padding.append('<span>' + result.msg + '</span>');
                    }
                }
            }).fail(function () {
                $('#loading').hide();
            });
        },
        // init_push: function () {
        //     var court_push = $("#_courtPush").empty();
        //     $(r.court_list).each(function (i, n) {
        //         court_push.append("<option value='" + n.courtid + "'>" + n.courtname + "</option>");
        //     });
        //     Class.select_courtroom(r.court_list[0].courtid);
        //     court_push.change(function () {
        //         var val = $(this).children('option:selected').val();
        //         Class.select_courtroom(val);
        //     })
        // },
        select_courtroom: function (id) {
            $.post(r.base_path + "sys/courtEquipment/selectCourtRoom", {courtId: id}, function (result) {
                if (result.data) {
                    $("#_courtRoom").empty();
                    $.each(result.data, function (i, n) {
                        $("#_courtRoom").append("<option value='" + n.uid + "'>" + n.courtroomname + "</option>");
                    });
                }
            }, 'json')
        },
        page: function (now, totalPages, callback) {
            base.pagination('#_page', {
                currentPage: now,
                totalPages: totalPages,
                onPageClicked: function (page) {
                    callback(page);
                }
            });
        }

    };
    init();
    //TODO 对外公开的方法写在这里
    window.p = {
        save: Class.save,
        dept_change: Class.dept_change
    };
}(window);